﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace Handday.Erp.Transfer
{
    /// <summary>
    /// 当前请求域信息
    /// </summary>
    public static class CurrentInfoMiddlewareExtensions
    {
        /// <summary>
        /// 当前信息中间件
        /// </summary>
        public static IApplicationBuilder UseCurrentInfo(this IApplicationBuilder builder)
        {
            builder.UseMiddleware<CurrentInfoMiddleware>();
            return builder;
        }
    }

    /// <summary>
    /// 当前请求域信息中间件
    /// </summary>
    public class CurrentInfoMiddleware
    {
        private readonly RequestDelegate _next;

        /// <summary>
        /// ctor
        /// </summary>
        public CurrentInfoMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        /// <summary>
        /// invoke
        /// </summary>
        public async Task InvokeAsync(HttpContext context, CurrentInfo currentInfo)
        {
            ulong.TryParse(context.Request.Query["corpId"], out var corpId);
            if (corpId <= 0)
            {
                ulong.TryParse(context.Request.Headers["corpId"], out corpId);
            }

            currentInfo.CorpId = corpId;
            await _next(context);
        }
    }
}
